package com.donglink.project.logmonitor.utils;

import com.donglink.project.logmonitor.domain.*;
import com.donglink.project.logmonitor.mapper.LogMonitorAppMapper;
import com.donglink.project.logmonitor.mapper.LogMonitorRuleMapper;
import com.donglink.project.logmonitor.mapper.LogMonitorUserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.storm.shade.org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class MonitorHandler {

    private static List< LogMonitorUser> userList;
    private static List<LogMonitorApp> appList;
    private static SqlSessionFactory sqlSessionFactory;
    private static List<LogMonitorRule> ruleList;
    ///初始化mybatis连接数据库
    static {
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);

            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);


        } catch (IOException e) {
            e.printStackTrace();
        }
        load();
    }


    private static boolean re=true;
    private static synchronized void reload()
    {

        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("mm");
        int m=Integer.parseInt(dateFormat.format(date));
        if(m%2==0&&re)
        {
            load();
            re=false;
        }



    }

    public static void tongbu()
    {
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("mm");
        int m=Integer.parseInt(dateFormat.format(date));
        if(m%2==0)
        {
            reload();
        }
        else
        {
            re=true;
        }
    }


    //加载数据库数据
    private static  void load()
    {
        initAppList();
        initUserList();
        initRuleList();
    }

    ///applist获取
    private static void initAppList()
    {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            LogMonitorAppMapper mapper = session.getMapper(LogMonitorAppMapper.class);
            appList= mapper.selectAll();

        }
    }

    private static void initUserList()
    {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            LogMonitorUserMapper mapper = session.getMapper(LogMonitorUserMapper.class);
            userList= mapper.selectAll();

        }
    }
    private static void initRuleList()
    {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            LogMonitorRuleMapper mapper = session.getMapper(LogMonitorRuleMapper.class);
            ruleList= mapper.selectAll();

        }
    }

    //将日志信息转化成message对象
    public static MyMessage parseMessage(String log)
    {
        //日志内容分为两个部分：由5个$$$$$符号作为分隔符，第一部分为appid，第二部分为日志内容。
        String[] messageArr = log.split("\\$\\$\\$\\$\\$");
        //对日志进行校验
        if (messageArr.length != 2) {
            return null;
        }
        if (StringUtils.isBlank(messageArr[0]) || StringUtils.isBlank(messageArr[1])) {
            return null;
        }
        //检验当前日志所属的appid是否是经过授权的。
        if (apppIdisValid(messageArr[0].trim())) {
            MyMessage message = new MyMessage();
            //赋值对象
            message.setAppId(messageArr[0].trim());
            message.setLine(messageArr[1]);
            return message;
        }
        return null;
    }




    private static boolean apppIdisValid(String trim) {

        for (LogMonitorApp app:appList)
        {
            if(Integer.parseInt(trim.trim())==app.getId())
            {
                //如果可用就返回true
                return true;
            }
        }
        return false;
    }

    //如果message触发了规则就返回true
    public static boolean triggerNotfy(MyMessage message) {
        for(LogMonitorRule rule:ruleList)
        {
            //appid和message的appid一样
            if(rule.getAppId()==Integer.parseInt(message.getAppId().trim()))
            {
                //如果有对应规则的关键字
                if(message.getLine().contains(new StringBuffer(rule.getKeyword())))
                {
                    message.setRuleId(String.valueOf( rule.getId()));
                    message.setKeyword(rule.getKeyword());
                    return true;
                }
            }
        }
        return false;
    }

    public static LogMonitorRuleRecord sendMail(MyMessage message) {

        LogMonitorRuleRecord record=new LogMonitorRuleRecord();
        record.setAppId(Integer.parseInt( message.getAppId()));
        record.setIsColse(0);
        record.setIsEmail(0);
        record.setIsPhone(0);
        record.setNoticeInfo(message.getLine());
        record.setRuleId(Integer.parseInt(message.getRuleId()));

        for(LogMonitorApp app:appList)
        {
            if(app.getId()==Integer.parseInt(message.getAppId()))
            {
                for(LogMonitorUser user:userList)
                {
                    if(user.getId()==app.getId())
                    {
                        try {
                            if(MailUtil.sendMail("error",message.toString(),user.getEmail()))
                            {

                                record.setIsEmail(1);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        }
        return record;

    }

    public static void saveRecordToSql(LogMonitorRuleRecord logMonitorRuleRecord) {
        System.out.println("写入到数据库"+logMonitorRuleRecord);
    }
}
